package nio;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;


/***
 * 这个类会报错，这个实验是失败的 over
 * */
public class Demo4 {

    public static void main(String[] args) throws IOException {

        //随机访问
        RandomAccessFile raf = new RandomAccessFile("/Users/mac/Desktop/服务器地址.txt","rw");
        //获取通道
        FileChannel channel = raf.getChannel();
        //分配指定大小指定缓冲区
        ByteBuffer buf1 = ByteBuffer.allocateDirect(100);
        ByteBuffer buf2 = ByteBuffer.allocateDirect(1027);
        //分散读取
        ByteBuffer[] bufs = {buf1,buf2};
        for(ByteBuffer buffer : bufs){
            buffer.flip();//开启读取模式
        }
        System.out.println(new String(bufs[0].array(),0,bufs[0].limit()));
        System.out.println("****************");
        System.out.println(new String(bufs[1].array(),0,bufs[1].limit()));
        RandomAccessFile raf2 = new RandomAccessFile("/Users/mac/Desktop/a.txt","rw");
        //获取写的通道
        FileChannel channel2 = raf2.getChannel();
        channel2.write(bufs);
        raf2.close();
        raf.close();
    }
}
